<template>
<div class="Row_content" style="width:965px;" id="market_active">
  <Form
      inline
      ref="formValidate"
      :model="formValidate"
      :rules="ruleValidate"
      :label-width="130">
      <FormItem label="活动名称:" prop="activityName">
        <Input v-model="formValidate.activityName" placeholder="请输入" class='input-wid' :maxlength="20" @on-keyup="filterSpace('activityName')" @on-blur="filterSpace('activityName')"></Input>
      </FormItem>
      <FormItem></FormItem>
      <FormItem label="开始时间:"
                prop="activityStart">
        <DatePicker :value="formValidate.activityStart"
                    type="datetime"
                    :editable="false"
                    placeholder="请选择"
                    style="width: 280px"
                    @on-change="activityStartChange"
                    :options="activityStartOptions"></DatePicker>
      </FormItem>
      <FormItem label="结束时间:"
                prop="activityEnd">
        <DatePicker :value="formValidate.activityEnd"
                    type="datetime"
                    :editable="false"
                    placeholder="请选择"
                    style="width: 280px"
                    @on-change="activityEndChange"
                    :options="activityEndOptions"></DatePicker>
      </FormItem>
      <FormItem label="营销渠道:" prop="channel" v-show="activityType === 0">
        <Select v-model="formValidate.channel" multiple>
          <Option v-for="(item, index) in channelList"
                  :value="item.value"
                  :key="index">
            {{ item.label }}
          </Option>
        </Select>
      </FormItem>
      <FormItem label="赠送积分:" prop="pointAmount" v-show="activityType === 0">
        <Input v-model="formValidate.pointAmount" placeholder="请输入" class='input-wid' :maxlength="9" @on-keyup="filterNum('pointAmount')" @on-blur="filterNum('pointAmount')"></Input>
      </FormItem>
      <FormItem label="面向会员:" prop="memberLevelIds" v-show="isGameType">
        <Select v-model="formValidate.memberLevelIds" multiple :max-tag-count="4" :max-tag-placeholder="() => '...'">
          <Option v-for="(item, index) in memberLevelList"
            :value="item.memberLevelId"
            :key="index">
            V{{ item.memberLevel }}
          </Option>
        </Select>
      </FormItem>
      <FormItem label="参与消耗积分:" prop="spendPrice" v-show="isGameType">
        <Input v-model="formValidate.spendPrice" placeholder="请输入" class='input-wid' :maxlength="9" @on-keyup="filterNum('spendPrice')" @on-blur="filterNum('spendPrice')"></Input>
      </FormItem>
      <FormItem label="次数限制:" style="width: 830px" class="tag-form ivu-form-item-required" v-show="isGameType">
        <div class="tag-container setting">
          <Form
            inline
            ref="settingValidate"
            :model="formValidate"
            :rules="ruleValidate"
            :label-width="150">
            <FormItem label="每人可抽奖:" style="width:250px;" prop="limitTimes">
              <Input v-model="formValidate.limitTimes" @on-keyup="filterNum1('limitTimes')" @on-blur="filterNum1('limitTimes')" style="width:120px;"
                :maxlength="6">
              </Input>
            </FormItem>
            <FormItem label="" style="width:200px;">
              <Select v-model="formValidate.limitType" class='input-wid' style="width:150px;">
                <Option v-for="(item, index) in limitList"
                  :value="item.value"
                  :key="index">
                  {{ item.label }}
                </Option>
              </Select>
            </FormItem>
            <FormItem label="每人最多中奖:" style="width:250px;" prop="winLimitTimes">
              <Input v-model="formValidate.winLimitTimes" @on-keyup="filterNum1('winLimitTimes')" @on-blur="filterNum1('winLimitTimes')" style="width:120px;"
                :maxlength="6">
              </Input>
            </FormItem>
            <FormItem label="" style="width:200px;">
              <Select v-model="formValidate.winLimitType" class='input-wid'  style="width:150px;">
                <Option v-for="(item, index) in limitList"
                  :value="item.value"
                  :key="index">
                  {{ item.label }}
                </Option>
              </Select>
            </FormItem>
          </Form>
        </div>
      </FormItem>
      <div class="add-level" v-show="activityType === 10" v-for="(rule, index) in formValidate.extraRule" :key="index">
        <p class="leveltt">V{{index}}升级V{{index+1}}</p>
        <FormItem label="赠送积分:" class='chunk' :prop="'extraRule.' + index + '.pointAmount'" :rules="[{required: true, message: '请输入赠送积分', trigger: 'blur'}]">
         <Input placeholder="请输入" class='input-wid' @on-keyup="filterLevelNum(index)" @on-blur="filterLevelNum(index)" :maxlength="9" v-model="rule.pointAmount"></Input>
        </FormItem>
        <FormItem label="优惠券:" class='chunk' :prop="'extraRule.' + index + '.couponList'" :rules="[{required: true, message: '请选择优惠券', trigger: 'change', type:'array', min:1}]">
          <select-coupon v-model="rule.couponList" @addcoupon="addLevelCoupon(index)"></select-coupon>
        </FormItem>
      </div>
      <FormItem label="优惠券:" style="width: 830px" prop="activityGiftList" v-show="activityType === 0">
        <select-coupon v-model="formValidate.activityGiftList" @addcoupon="Dmodal = true"></select-coupon>
      </FormItem>
      <!-- <FormItem label="推送微信消息:" prop="isPushMessage" v-show="activityType === 0">
        <Select v-model="formValidate.isPushMessage" placeholder="请选择" class='input-wid'>
          <Option :value="item.value" :key="index" v-for="(item, index) in pushMsgList">{{ item.label }}</Option>
        </Select>
      </FormItem>
      <FormItem v-show="activityType === 0"></FormItem>
      <FormItem label="消息模板:" style="width: 830px" v-show="activityType === 0">
        <Input v-model="formValidate.activityRule"
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 8 }"
          :maxlength="300"
          placeholder="请输入"
          class="Row_content_input"></Input>
      </FormItem> -->
      <FormItem label="活动规则:" style="width: 830px" prop="activityRule" v-show="isGameType">
        <div ref="addEditor" class="rich-editor" style="width:700px;"></div>
        <!-- <Input v-model="formValidate.activityRule"
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 8 }"
          :maxlength="300"
          placeholder="请输入"
          style="width:700px"></Input> -->
          <!-- <div style="margin-left:10px;color: #808695;width:690px; text-align:right;">{{formValidate.activityRule.length}}/2000</div> -->
      </FormItem>
      <FormItem label="分享标题:" prop="shareTitle" v-show="isGameType || activityType === 11">
        <Input v-model="formValidate.shareTitle" @on-keyup="filterSpace('shareTitle')" @on-blur="filterSpace('shareTitle')" class="input-wid" :maxlength="20"></Input>
      </FormItem>
      <FormItem v-show="isGameType"></FormItem>
      <FormItem label="分享封面:" class="upload-img" prop="shareImage" v-show="isGameType || activityType === 11">
        <Row type="flex" align="top">
          <Col v-if="isGameType">
            <img :src="shareImg[activityType - 1]" style="display: inline-block;width:96px;height:96px;vertical-align: top;" alt="">
          </Col>
          <Col v-show="activityType === 11" >
            <Upload ref="upload"
              :format="['jpg','png']"
              :max-size="500"
              :on-success="handleSuccess"
              :on-format-error="handleFormatError"
              :on-exceeded-size="handleMaxSize"
              type="drag"
              :action="$config.uploadImg"
              :show-upload-list="false"
              style="display: inline-block;width:96px">
              <img :src="formValidate.shareImage ? formValidate.shareImage : defaultUrl"
                style="display: inline-block;width:96px;height:96px;vertical-align: top;"
                alt="" />
            </Upload>
            <p v-if="formValidate.shareImage && imgloaded" class="replace_tit" @click="delHeadImage">删除</p>
          </Col>
        </Row>
      </FormItem>
      <FormItem label="单个分享链接最多领取人数/人:" style="width: 830px" prop="limitTimes" class="largeLabel" v-show="activityType === 11">
        <Input v-model="formValidate.limitTimes" @on-keyup="filterNum1('limitTimes')" @on-blur="filterNum1('limitTimes')" style="width:240px;"
          :maxlength="9">
        </Input>
      </FormItem>
      <FormItem label="每人每天最多领取红包数量/个:" style="width: 830px" prop="winLimitTimes" class="largeLabel" v-show="activityType === 11">
        <Input v-model="formValidate.winLimitTimes" @on-keyup="filterNum1('winLimitTimes')" @on-blur="filterNum1('winLimitTimes')" style="width:240px;"
          :maxlength="9">
        </Input>
      </FormItem>
      <div class="add-level" v-show="activityType === 11">
        <p class="leveltt">获得红包类型及概率</p>
        <FormItem label="红包列表:" class='chunk' prop="activityGiftList">
          <select-redpack v-model="formValidate.activityGiftList" @addcoupon="Dmodal = true"></select-redpack>
        </FormItem>
      </div>
      <FormItem label="推送微信消息:" prop="sendWechat" v-show="activityType === 0 || activityType === 10">
        <Select v-model="formValidate.sendWechat" @on-change="selectWechatChange">
          <Option v-for="(item, index) in sendWechats"
                  :value="item.id"
                  :key="index">
            {{ item.templateName }}
          </Option>
        </Select>
      </FormItem>
      <FormItem label="推送短信消息:" prop="sendMessage" v-show="activityType === 0 || activityType === 10">
        <Select v-model="formValidate.sendMessage" @on-change="selectMessageChange">
          <Option v-for="(item, index) in sendMessages"
                  :value="item.id"
                  :key="index">
            {{ item.templateName }}
          </Option>
        </Select>
      </FormItem>
      <FormItem label="微信消息模板:" style="width: 830px" v-show="formValidate.sendWechat !== '-1'">
        <Input
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 8 }"
          style="width:700px" disabled v-model="wechat"></Input>
      </FormItem>
      <FormItem label="短信消息模板:" style="width: 830px" v-show="formValidate.sendMessage !== '-1'">
        <Input
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 8 }"
          style="width:700px" disabled v-model="message"></Input>
      </FormItem>
      <FormItem label="活动说明:" style="width: 830px"  v-show="activityType === 0 || activityType === 10">
        <Input v-model="formValidate.activityRule"
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 8 }"
          :maxlength="200"
          placeholder="请输入"
          style="width:700px"></Input>
          <div style="margin-left:10px;color: #808695;width:690px; text-align:right;">{{formValidate.activityRule.length}}/200</div>
      </FormItem>
      <FormItem label="活动说明:" style="width: 830px" prop="activityRule" v-show="activityType === 11">
        <Input v-model="formValidate.activityRule"
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 8 }"
          :maxlength="500"
          placeholder="请输入"
          style="width:700px"></Input>
          <div style="margin-left:10px;color: #808695;width:690px; text-align:right;">{{formValidate.activityRule.length}}/500</div>
      </FormItem>
      <FormItem v-show="isGameType"></FormItem>
      <FormItem label="选择奖品:" style="width: 830px" prop="activityGiftList" v-show="isGameType">
        <select-gift v-model="formValidate.activityGiftList" @addgift="handleAddGift" @addcoupon="handleGiftCoupon"></select-gift>
        <span style="position:absolute; left:-118px; top:20px;font-size:12px;">(最多选择五个奖品)</span>
      </FormItem>
      <FormItem label="未中奖概率:" v-show="isGameType" prop="missRate">
        <Input v-model="formValidate.missRate" @on-keyup="filterNum2('missRate')" @on-blur="filterNum2('missRate')" class="input-wid" :maxlength="3"></Input><span style="position:absolute;right:-20px;">%</span>
      </FormItem>
      <FormItem label="未中奖展示:" v-show="isGameType" prop="reminder">
        <Input v-model="formValidate.reminder" @on-keyup="filterSpace('reminder')" @on-blur="filterSpace('reminder')" class="input-wid" :maxlength="8"></Input>
      </FormItem>
      <div class="form-btn"
              style="margin-top: 5px; padding-left:130px; width: 800px;">
      <Button class="system-submit-btn" v-if="isGameType"
              @click="handleSubmit('preview')"
              >预览</Button>
      <Button type="primary"
              class="system-submit-btn"
              @click="handleSubmit('submit')"
              >确定</Button>
      <Button class="system-submit-btn"
        @click="handleReset"
        style="margin-left: 8px">取消</Button>
    </div>
  </Form>
  <drawer-coupon v-model="Dmodal" :data="formValidate.activityGiftList" :origin="couponOriginType" @sure="handleSelectCoupon" :maxsize="activityType==11 ? 10: 20"></drawer-coupon>
  <drawer-coupon-single v-model="Smodal" :data="activityGiftSingle" :origin="couponOriginType" @sure="handleSingleCoupon"></drawer-coupon-single>
  <Modal v-model="dialogPreview" width="430" title="预览">
    <div style="text-align:center;height:550px; width:400px; overflow-y:scroll;">
        <div :class="'gamebg' + activityType">
          <span>{{ formValidate.spendPrice }} 积分</span>
          <p v-html="formValidate.activityRule"></p>
          <div :class="['zhuanpanbox', 'z' + (formValidate.activityGiftList.length + 1)]">
            <div :class="['name', 'name' + index]" v-for="(item, index) in formValidate.activityGiftList" :key="index">{{ item.activityGiftName }}</div>
            <div :class="['name', 'name' + formValidate.activityGiftList.length]" >
              {{ formValidate.reminder }}
            </div>
            <img src="./imgs/game_start.png" width="87" height="100" class="zhizheng">
          </div>
        </div>
    </div>
    <div slot="footer">
        <Button @click="dialogPreview = false">关闭</Button>
    </div>
  </Modal>
</div>
</template>

<script>
import { routeEqual } from '@/libs/util'
import { mapState } from 'vuex'
import { saveActive } from '@/api/market/active.js'
import { getMemberLevelList } from '@/api/member/index.js'
import { getMessages } from '@/api/market/message'
import DrawerCoupon from '@/view/components/drawer-coupon/index.vue'
import SelectCoupon from '@/view/components/select-coupon/index.vue'
import SelectGift from '@/view/components/select-gift/index.vue'
import SelectRedpack from '@/view/components/select-redpack/index.vue'
import DrawerCouponSingle from '@/view/components/drawer-coupon/single.vue'
import editor from '@/view/components/editor/mixins'
import enumsMixin from '../enums.js'
let shareImg = [ require('./imgs/share1.jpg'), require('./imgs/share2.jpg'), require('./imgs/share3.jpg') ]
export default {
  name: 'market_active_create',
  components: { SelectCoupon, SelectGift, DrawerCoupon, DrawerCouponSingle, SelectRedpack },
  mixins: [editor, enumsMixin],
  data () {
    return {
      shareImg: shareImg,
      activityType: 0,
      formValidate: {
        activityName: '',
        activityStart: '',
        activityEnd: '',
        channel: [],
        memberLevelIds: [],
        activityGiftList: [],
        pointAmount: '',
        isPushMessage: '',
        activityRule: '',
        spendPrice: '',
        limitTimes: '',
        limitType: 0,
        giveScore: '',
        winLimitTimes: '',
        winLimitType: 0,
        shareTitle: '',
        shareImage: '',
        missRate: '',
        reminder: '',
        extraRule: [],
        sendWechat: '-1',
        sendMessage: '-1'
      },
      sendWechats: [{ templateName: '无', id: '-1' }],
      sendMessages: [{ templateName: '无', id: '-1' }],
      wechat: '',
      message: '',
      activityStartOptions: {},
      activityEndOptions: {},
      ruleValidate: {
        activityName: { required: true, message: '请填写活动名称', trigger: 'blur' },
        activityStart: {
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (!new Date(this.formValidate.activityStart).getTime()) {
              callback(new Error('请选择开始时间'))
            } else if (new Date(this.formValidate.activityStart).getTime() > new Date(this.formValidate.activityEnd).getTime() || new Date(this.formValidate.activityStart).getTime() === new Date(this.formValidate.activityEnd).getTime()) {
              callback(new Error('开始时间要小于结束时间'))
            } else {
              callback()
            }
          }
        },
        activityEnd: {
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (!new Date(this.formValidate.activityEnd).getTime()) {
              callback(new Error('请选择结束时间'))
            } else if (new Date(this.formValidate.activityStart).getTime() > new Date(this.formValidate.activityEnd).getTime() || new Date(this.formValidate.activityStart).getTime() === new Date(this.formValidate.activityEnd).getTime()) {
              callback(new Error('结束时间要大于开始时间'))
            } else if (new Date().getTime() > new Date(this.formValidate.activityEnd).getTime()) {
              callback(new Error('结束时间要大于当前系统时间'))
            } else {
              callback()
            }
          }
        },
        sendWechat: { required: true, message: '请选择是否发送微信消息' },
        sendMessage: { required: true, message: '请选择是否发送短信消息' },
        channel: { required: true, message: '请选择营销渠道' },
        isPushMessage: { required: true, message: '请选择推送微信消息' },
        activityRule: { required: true, message: '请填写活动规则', trigger: 'blur' },
        pointAmount: { required: true, message: '请填写赠送积分', trigger: 'blur' },
        extraRule: { required: true, message: '请设置升级礼包' },
        activityGiftList: { required: true, message: '请添加优惠券' },
        spendPrice: { required: true, message: '请填写参与消耗积分', trigger: 'blur' },
        memberLevelIds: { required: true, message: '请选择面向会员' },
        limitTimes: { required: true, message: '请填写每人可抽奖', trigger: 'blur' },
        winLimitTimes: { required: true, message: '请填写每人最多中奖', trigger: 'blur' },
        shareTitle: { required: true, message: '请填写分享标题', trigger: 'blur' },
        shareImage: { required: true, message: '请上传分享图片', trigger: 'change' },
        missRate: { required: true, message: '请填写未中奖概率', trigger: 'blur' },
        reminder: { required: true, message: '请填写未中奖展示', trigger: 'blur' }
      },
      imgloaded: false,
      defaultUrl: require('@/assets/images/add.png'),
      memberLevelList: [],
      Smodal: false,
      Dmodal: false,
      tempGiftIndex: null,
      tempLevelIndex: null,
      couponOriginType: 2,
      submitLock: false,
      dialogPreview: false,
      activityGiftSingle: {}
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      if (vm.type !== parseInt(to.params.type)) {
        vm.type = parseInt(to.params.type)
        vm.getDetail()
      }
    })
  },
  computed: {
    ...mapState({
      merchantId: state => state.user.merchantId,
      userId: state => state.user.userId,
      userName: state => state.user.userName
    }),
    isGameType () {
      return this.activityType === 1 || this.activityType === 2 || this.activityType === 3
    }
  },
  mounted () {
    setTimeout(() => {
      if (this.isGameType) {
        this.createEditor(this.$refs.addEditor, () => {
          if (this.$editor.txt.html() === '<p><br></p>') {
            this.formValidate.activityRule = ''
          } else {
            this.formValidate.activityRule = this.$editor.txt.html()
          }
        })
      }
    }, 0)
  },
  methods: {
    getDetail () {
      this.activityType = parseInt(this.$route.params.type)
      if (this.$refs.settingValidate) {
        this.$refs.settingValidate.resetFields()
      }
      if (this.$refs.formValidate) {
        this.$refs.formValidate.resetFields()
      }
      if (this.activityType === 0) {
        this.channelList = this.channelRegList
        this.formValidate.shareImage = ''
        this.ruleValidate.channel.required = true
        this.ruleValidate.isPushMessage.required = true
        this.ruleValidate.activityRule.required = false
        this.ruleValidate.pointAmount.required = true
        this.ruleValidate.memberLevelIds.required = false
        this.ruleValidate.spendPrice.required = false
        this.ruleValidate.limitTimes.required = false
        this.ruleValidate.winLimitTimes.required = false
        this.ruleValidate.shareTitle.required = false
        this.ruleValidate.shareImage.required = false
        this.ruleValidate.missRate.required = false
        this.ruleValidate.reminder.required = false
        this.ruleValidate.activityGiftList.required = true
        this.ruleValidate.extraRule.required = false
      }
      if (this.isGameType) {
        this.formValidate.shareImage = ''
        this.ruleValidate.channel.required = false
        this.ruleValidate.isPushMessage.required = false
        this.ruleValidate.activityRule.required = true
        this.ruleValidate.pointAmount.required = false
        this.ruleValidate.memberLevelIds.required = true
        this.ruleValidate.spendPrice.required = true
        this.ruleValidate.limitTimes.required = true
        this.ruleValidate.winLimitTimes.required = true
        this.ruleValidate.shareTitle.required = true
        this.ruleValidate.shareImage.required = false
        this.ruleValidate.missRate.required = true
        this.ruleValidate.reminder.required = true
        this.ruleValidate.activityGiftList.required = true
        this.ruleValidate.extraRule.required = false
        this.ruleValidate.activityGiftList.message = '请添加奖品'
        this.ruleValidate.activityRule.message = '请填写活动规则'
      }
      if (this.activityType === 10) {
        this.formValidate.shareImage = ''
        this.ruleValidate.channel.required = false
        this.ruleValidate.isPushMessage.required = false
        this.ruleValidate.activityRule.required = false
        this.ruleValidate.pointAmount.required = false
        this.ruleValidate.memberLevelIds.required = false
        this.ruleValidate.spendPrice.required = false
        this.ruleValidate.limitTimes.required = false
        this.ruleValidate.winLimitTimes.required = false
        this.ruleValidate.shareTitle.required = false
        this.ruleValidate.shareImage.required = false
        this.ruleValidate.missRate.required = false
        this.ruleValidate.reminder.required = false
        this.ruleValidate.activityGiftList.required = false
        this.ruleValidate.extraRule.required = true
      }
      if (this.activityType === 11) {
        this.formValidate.shareImage = ''
        this.ruleValidate.channel.required = false
        this.ruleValidate.isPushMessage.required = false
        this.ruleValidate.activityRule.required = true
        this.ruleValidate.pointAmount.required = false
        this.ruleValidate.memberLevelIds.required = false
        this.ruleValidate.spendPrice.required = false
        this.ruleValidate.limitTimes.required = true
        this.ruleValidate.winLimitTimes.required = true
        this.ruleValidate.shareTitle.required = true
        this.ruleValidate.shareImage.required = true
        this.ruleValidate.missRate.required = false
        this.ruleValidate.reminder.required = false
        this.ruleValidate.activityGiftList.required = true
        this.ruleValidate.extraRule.required = false
        this.ruleValidate.activityRule.message = '请填写活动说明'
      }
      if (this.activityType !== 0) {
        getMemberLevelList({
          merchantId: this.merchantId
        }).then(res => {
          const result = res.data || {}
          if (result.status === 200) {
            this.memberLevelList = result.data
            if (this.activityType === 10) {
              result.data.slice(0, result.data.length - 1).forEach((item, i) => {
                this.$set(this.formValidate.extraRule, i, {
                  pointAmount: '',
                  couponList: []
                })
              })
            }
          } else {
            this.$Message.error(`${result.error}`)
          }
        }).catch(err => {
          this.$Message.error(`${err}`)
        })
      }
      if (this.activityType === 0 || this.activityType === 10) {
        this.getEnums(1).then(data => {
          this.sendWechats = [{ templateName: '无', id: '-1' }].concat(data || [])
        })
        this.getEnums(2).then(data => {
          this.sendMessages = [{ templateName: '无', id: '-1' }].concat(data || [])
        })
      }
    },
    filterLevelNum (i) {
      let val = this.formValidate.extraRule[i].pointAmount
      val = val.replace(/\D/g, '')
      if (val.length > 1 && val.substring(0, 1) === '0') {
        val = '0'
      }
      this.formValidate.extraRule[i].pointAmount = val
    },
    filterNum (name) {
      let val = this.formValidate[name]
      val = val.replace(/\D/g, '')
      if (val.length > 1 && val.substring(0, 1) === '0') {
        val = '0'
      }
      this.formValidate[name] = val
    },
    filterNum1 (name) {
      let val = this.formValidate[name]
      val = val.replace(/\D/g, '')
      if (val.substring(0, 1) === '0') {
        val = ''
      }
      this.formValidate[name] = val
    },
    filterNum2 (name) {
      let val = this.formValidate[name]
      val = val.replace(/[^0-9]/g, '')
      if (val.length > 1 && val.substring(0, 1) === '0') {
        val = '0'
      }
      if (val.length === 3 && val > 100) {
        val = val.substring(0, 2)
      }
      this.formValidate[name] = val
    },
    filterSpace (prop) {
      this.formValidate[prop] = this.formValidate[prop].replace(/[^0-9A-Za-z\u4e00-\u9fa5]/g, '')
    },
    activityStartChange (time) {
      this.formValidate.activityStart = time
      this.activityEndOptions = {
        disabledDate (date) {
          return date.valueOf() < new Date(time.split(' ')[0]).getTime() - 24 * 3600 * 1000
        }
      }
    },
    activityEndChange (time) {
      this.formValidate.activityEnd = time
      this.activityStartOptions = {
        disabledDate (date) {
          return date.valueOf() > new Date(time).getTime()
        }
      }
    },
    handleSelectCoupon (val) {
      if (this.activityType === 0 || this.activityType === 10) {
        let data = JSON.parse(JSON.stringify(val)).map(item => {
          item.hitRate = 1
          item.activityGiftName = item.refName
          return item
        })
        if (this.activityType === 0) {
          this.formValidate.activityGiftList = data
        } else {
          this.formValidate.extraRule[this.tempLevelIndex].couponList = data
          this.$refs.formValidate.validateField('extraRule.' + this.tempLevelIndex + '.couponList')
        }
      }
      if (this.activityType === 11) {
        let data = JSON.parse(JSON.stringify(val)).map(item => {
          item.hitRate = item.hitRate ? item.hitRate : ''
          item.activityGiftName = item.refName
          return item
        })
        this.formValidate.activityGiftList = data
      }
    },
    handleSingleCoupon (val) {
      if (this.formValidate.activityGiftList.filter((item, i) => item.refId === val.refId && this.tempGiftIndex !== i).length > 0) {
        this.$Message.error('不能添加相同的优惠券奖品')
        return
      }
      this.Smodal = false
      this.$set(this.formValidate.activityGiftList, this.tempGiftIndex, Object.assign(this.formValidate.activityGiftList[this.tempGiftIndex], { ...val }))
    },
    handleAddGift () {
      this.formValidate.activityGiftList.push({
        activityGiftName: '',
        refName: '',
        giftType: '',
        refType: '',
        pointAmount: '',
        couponType: '',
        hitRate: '',
        giftAmount: ''
      })
    },
    handleGiftCoupon (i) {
      this.Smodal = true
      this.tempGiftIndex = i
      this.activityGiftSingle = this.formValidate.activityGiftList[i] ? this.formValidate.activityGiftList[i] : {}
    },
    addLevelCoupon (index) {
      this.Dmodal = true
      this.tempLevelIndex = index
      this.formValidate.activityGiftList = JSON.parse(JSON.stringify(this.formValidate.extraRule[index].couponList))
    },
    handlePreview () {
      this.dialogPreview = true
    },
    handleSubmit (type) {
      let valid = true
      if (this.isGameType) {
        this.$refs.settingValidate.validate(val => {
          valid = val
        })
        if (this.$editor.txt.html().length > 2000) {
          this.$Message.error('活动规则不能超过2000个字符')
          return
        }
      }
      this.$refs.formValidate.validate(val => {
        if (val && valid) {
          const formValidate = this.formValidate
          if (new Date(formValidate.activityStart).getTime() > new Date(formValidate.activityEnd).getTime()) {
            this.$Message.error('开始时间不能大于结束时间')
            return
          }
          let params = {
            merchantId: this.merchantId,
            activityName: formValidate.activityName,
            activityType: this.activityType,
            activityStart: formValidate.activityStart,
            activityEnd: formValidate.activityEnd,
            activityRule: formValidate.activityRule,
            creatorName: this.userName,
            creatorId: this.userId
          }
          if (this.isGameType) {
            if (formValidate.activityGiftList.filter(item => (item.refType === '' || item.hitRate === '' || item.activityGiftName === '' || item.giftAmount === '') || (item.refType === 3 && item.pointAmount === '')).length > 0) {
              this.$Message.error('请完善奖品信息')
              return
            }
            let total = 0
            formValidate.activityGiftList.forEach((item) => {
              total = total + parseInt(item.hitRate)
            })
            if (total + parseInt(formValidate.missRate) !== 100) {
              this.$Message.error('概率设置错误')
              return
            }
            params = {
              ...params,
              memberLevelIds: formValidate.memberLevelIds.join(','),
              shareTitle: formValidate.shareTitle,
              missRate: formValidate.missRate / 100,
              reminder: formValidate.reminder,
              limitType: formValidate.limitType,
              limitTimes: formValidate.limitTimes,
              winLimitType: formValidate.winLimitType,
              winLimitTimes: formValidate.winLimitTimes,
              activityCostRule: {
                spendType: 0,
                spendPrice: formValidate.spendPrice
              },
              activityGiftList: formValidate.activityGiftList.map((item, i) => {
                let obj = JSON.parse(JSON.stringify(item))
                obj.hitRate = obj.hitRate / 100
                obj.giftNo = i + 1
                return obj
              })
            }
          }
          if (this.activityType === 0) {
            let giftList = formValidate.activityGiftList.map((item, i) => {
              let obj = JSON.parse(JSON.stringify(item))
              obj.giftNo = i + 1
              return obj
            })
            giftList.push({
              pointAmount: formValidate.pointAmount,
              refType: 3,
              hitRate: 1
            })
            params = {
              ...params,
              // channel: formValidate.channel.length === 2 ? '*' : formValidate.channel.join(','),
              channel: formValidate.channel.join(','),
              isPushMessage: formValidate.isPushMessage,
              activityGiftList: giftList
            }
          }
          if (this.activityType === 10) {
            let levelObj = {}
            let activityGiftList = []
            formValidate.extraRule.forEach((item, i) => {
              levelObj[i] = [{
                refType: 3,
                hitRate: 1,
                giftNo: 0,
                pointAmount: item.pointAmount
              }]
              let couponList = item.couponList.map((coupon, n) => {
                let obj = JSON.parse(JSON.stringify(coupon))
                obj.hitRate = 1
                obj.giftNo = n + 1
                return obj
              })
              levelObj[i] = levelObj[i].concat(couponList)
              activityGiftList = activityGiftList.concat(couponList)
            })
            params = {
              ...params,
              isPushMessage: formValidate.isPushMessage,
              activityGiftList: activityGiftList,
              extraRule: levelObj
            }
          }
          if (this.activityType === 11) {
            if (formValidate.activityGiftList.filter(item => item.hitRate === '').length > 0) {
              this.$Message.error('请设置红包获得概率')
              return
            }
            params = {
              ...params,
              isPushMessage: formValidate.isPushMessage,
              limitTimes: formValidate.limitTimes,
              winLimitTimes: formValidate.winLimitTimes,
              shareTitle: formValidate.shareTitle,
              shareImage: formValidate.shareImage,
              activityGiftList: formValidate.activityGiftList.map((item, i) => {
                let obj = JSON.parse(JSON.stringify(item))
                obj.hitRate = obj.hitRate / 100
                obj.giftNo = i + 1
                return obj
              })
            }
          }
          if (this.activityType === 0 || this.activityType === 10) {
            let templates = []
            if (formValidate.sendWechat !== '-1') {
              templates.push({
                templateId: formValidate.sendWechat,
                templateType: 1
              })
            }
            if (formValidate.sendMessage !== '-1') {
              templates.push({
                templateId: formValidate.sendMessage,
                templateType: 2
              })
            }
            params.templates = templates
          }
          if (type === 'submit') {
            this.handleSave(params)
          }
          if (type === 'preview') {
            this.handlePreview()
          }
        }
      })
    },
    handleSave (params) {
      if (this.submitLock) {
        return
      }
      this.submitLock = true
      saveActive(params).then(res => {
        this.submitLock = false
        const result = res.data || {}
        if (result.status === 200) {
          this.$Message.success('新增成功！')
          this.handleReset()
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.submitLock = false
        this.$Message.error(`${err}`)
      })
    },
    handleReset () {
      this.$store.commit('closeTag', this.$route)
      this.$store.commit('setTagNavList', this.$store.state.app.tagNavList.filter(item => !routeEqual(this.$route, item)))
      this.$nextTick(() => {
        this.$router.push({
          name: 'market_active_list'
        })
      })
    },
    selectWechatChange (value) {
      this.formValidate.sendWechat = value
      if (value) {
        this.sendWechats.forEach(item => {
          if (item.id === value) {
            this.wechat = item.content
          }
        })
      } else {
        this.wechat = ''
      }
    },
    selectMessageChange (value) {
      this.formValidate.sendMessage = value
      if (value) {
        this.sendMessages.forEach(item => {
          if (item.id === value) {
            this.message = item.content
          }
        })
      } else {
        this.message = ''
      }
    },
    getEnums (templateType) {
      return new Promise((resolve, reject) => {
        getMessages({
          templateType,
          merchantId: this.merchantId,
          suitableType: this.activityType,
          status: 1
        }).then(res => {
          const result = res.data || {}
          if (result.status === 200) {
            resolve(result.data)
          } else {
            this.$Message.error(`${result.error}`)
          }
        }).catch(err => {
          this.$Message.error(`${err}`)
        })
      })
    },
    handleMaxSize (file) {
      this.$Message.warning('上传的图片大小不能超过500k')
    },
    handleFormatError (file) {
      this.$Message.warning('上传的图片格式错误')
    },
    handleSuccess (response, file, fileList) {
      this.formValidate.shareImage = response.full_img_url
      this.imgloaded = true
    },
    delHeadImage () {
      this.imgloaded = false
      this.formValidate.shareImage = ''
    }
  }
}
</script>
<style lang='less' scoped>
  .replace_tit{
    position: absolute;
    left: 0;
    top: 72px;
    width: 96px;
    height: 24px;
    line-height: 24px;
    text-align: center;
    opacity: 0.8;
    background: #ED4014;
    color: #fff;
  }
  .gamebg1{
    width: 375px;
    position: relative;
    min-height: 857px;
    background: url(./imgs/game1.jpg) no-repeat 0 0 #91c03b;
    span{
      position: absolute;
      left: 220px;
      top: 325px;
      color: #fff;
      font-size: 16px;
    }
    p{
      padding:680px 20px 20px;
      color: #3e6201;
      font-size: 14px;
      text-align:justify;
      word-break: break-all;
    }
  }
  .zhuanpanbox{ display: none;}
  .gamebg2{
    width: 375px;
    position: relative;
    min-height: 1046px;
    background: url(./imgs/game2.jpg) no-repeat 0 0 #feeac8;
    span{
      position: absolute;
      left: 220px;
      top: 268px;
      color: #fff;
      font-size: 16px;
    }
    p{
      padding:870px 20px 20px;
      color: #a46427;
      font-size: 14px;
      text-align:justify;
      word-break: break-all;
    }
    .zhuanpanbox{
      display:block;
      width:375px;
      height: 375px;
      position: absolute;
      left:0;
      top: 281px;
    }
    .name{
      position: absolute;
      line-height:20px;
      font-size: 14px;
      width: 80px;
      text-align: center;
    }
    .z2{ background: url(./imgs/wheel2.png) no-repeat 0 0;
    .name0{
            top: 50%;
            margin-top: -20px;
            right:50px;
            color: #FFFFFF;
            transform: rotate(90deg);}
    .name1{
            top: 50%;
            margin-top: -20px;
            left:50px;
            color: #CB2B2B;
            transform: rotate(270deg);}
    }
    .z3{ background: url(./imgs/wheel3.png) no-repeat 0 0;
      .name0{
        color: #FFFFFF;
        top:132px;
        right:69px;
        transform: rotate(60deg);
      }
      .name1{
        color:#CB2B2B;
        bottom:81px;
        left:147px;
        transform:rotate(180deg);
      }
      .name2{
        color:#FFFFFF;
        top:132px;
        left:69px;
        transform:rotate(300deg);
      }
    }
    .z4{ background: url(./imgs/wheel4.png) no-repeat 0 0;
      .name0{
        color: #FFFFFF;
        top:115px;
        right:84px;
        transform: rotate(45deg);
      }
      .name1{
        color: #CB2B2B;
        bottom:115px;
        right:84px;
        transform: rotate(135deg);
      }
      .name2{
        color: #FFFFFF;
        bottom:115px;
        left:84px;
        transform: rotate(225deg);
      }
      .name3{
        color: #CB2B2B;
        top:115px;
        left:84px;
        transform: rotate(315deg);
      }
    }
    .z5{ background: url(./imgs/wheel5.png) no-repeat 0 0;
      .name0{
        color:#FFFFFF;
        top:98px;
        right:95px;
        transform: rotate(36deg);
      }
      .name1{
        color:#CB2B2B;
        top:195px;
        right:59px;
        transform: rotate(108deg);
      }
      .name2{
        color:#FFFFFF;
        top:260px;
        right:145px;
        transform: rotate(180deg);
      }
      .name3{
        color:#CB2B2B;
        top:195px;
        left:59px;
        transform: rotate(252deg);
      }
      .name4{
        color:#FFFFFF;
        top:102px;
        left:95px;
        transform: rotate(324deg);
      }
    }
    .z6{ background: url(./imgs/wheel6.png) no-repeat 0 0;
      .name0{
        color:#FFFFFF;
        top:90px;
        right:104px;
        transform: rotate(30deg);
      }
      .name1{
        color:#CB2B2B;
        top:170px;
        right:55px;
        transform: rotate(90deg);
      }
      .name2{
        color:#FFFFFF;
        bottom:90px;
        right:104px;
        transform: rotate(150deg);
      }
      .name3{
        color:#CB2B2B;
        bottom:90px;
        left:104px;
        transform: rotate(210deg);
      }
      .name4{
        color:#FFFFFF;
        top:170px;
        left:52px;
        transform: rotate(270deg);
      }
      .name5{
        color:#CB2B2B;
        top:90px;
        left:104px;
        transform: rotate(330deg);
      }
    }
    .zhizheng{
      position: absolute;
      top:128px;
      left: 145px;
    }
  }
  .gamebg3{
    width: 375px;
    position: relative;
    min-height: 891px;
    background: url(./imgs/game3.jpg) no-repeat 0 0 #b57841;
    span{
      position: absolute;
      left: 220px;
      top: 273px;
      color: #f1dd1f;
      font-size: 16px;
    }
    p{
      padding:710px 20px 20px;
      color: #592e13;
      font-size: 14px;
      text-align:justify;
      word-break: break-all;
    }
  }
</style>
<style lang='less'>
  #market_active{
    .largeLabel{
      .ivu-form-item-label{
        width:240px !important;
      }
      .ivu-form-item-content{
        margin-left: 240px !important;
      }
    }
    .input-wid{
      width: 280px;
    }
    .leveltt{
      font-size: 14x;
      font-weight: bold;
      margin-left: 60px;
      padding-bottom: 20px;
    }
    .add-level{
      position: relative;
      border: 1px solid #E9E9E9;
      border-radius: 3px;
      margin-bottom: 24px;
      padding-top: 20px;
    }
    .chunk{
      display: block;
    }
    .tag-form {
    .ivu-form-item-content {
      width: 700px;
    }
    .tag-container {
      display: flex;
      flex-wrap: wrap;
      min-height: 32px;
      padding: 4px 7px;
      min-width: 280px;
      border: 1px solid #dcdee2;
      border-radius: 4px;
      cursor: pointer;
      text-align: left;
      &.setting {
        background: #F8F8F9;
        padding: 20px 30px 0 10px;
        .ivu-form {
          display: flex;
          align-items: center;
          flex-wrap: wrap;
          width: 100%;
          .ivu-form-item-content {
            display: flex;
            align-items: center;
            width: 150px
          }
          .ivu-form-item {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
          }
          .ivu-form-item-label {
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }
        }
      }
    }
  }
}
</style>
